package com.yueyang.sojourn.server.service.share;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yueyang.sojourn.server.common.baymax.web.result.exception.StandardBusinessException;
import com.yueyang.sojourn.server.model.enums.ShareDataTypeEnum;
import com.yueyang.sojourn.server.model.po.ShareData;
import com.yueyang.sojourn.server.model.vo.ShareDataVo;
import com.yueyang.sojourn.server.model.vo.ShareDistributorVo;
import com.yueyang.sojourn.server.model.vo.ShareVo;
import com.yueyang.sojourn.server.model.vo.UploadResult;
import com.yueyang.sojourn.server.service.FileService;
import com.yueyang.sojourn.server.utils.PhoneNumberUtil;
import jk.excel.ExcelConfig;
import jk.excel.ExcelHeader;
import jk.excel.ExcelUtil;
import jk.excel.cellinfo.CellInfo;
import jk.excel.cellinfo.Colors;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * 分销数据service
 */
@Service
@Slf4j
public class ShareDataService {
    @Autowired
    private ShareDataMapper shareDataMapper;
    @Autowired
    private ShareService shareService;
    @Autowired
    private FileService fileService;

    public void insert(ShareData shareData) {
        this.shareDataMapper.insert(shareData);
    }

    public void actionForMessage(ShareData shareData) {
        this.insert(shareData);
        this.updateShare(shareData.getShareId(), ShareDataTypeEnum.findByCode(shareData.getType()).get());
    }

    /**
     * 更新主表冗余数据
     * @param shareId
     * @param type
     */
    private void updateShare(Long shareId, ShareDataTypeEnum type) {
        if (type == ShareDataTypeEnum.浏览) {
            this.shareService.visitIncrease(shareId);
        }
        else if (type == ShareDataTypeEnum.注册) {
            this.shareService.registIncrease(shareId);
        }
        else if (type == ShareDataTypeEnum.下单) {
            this.shareService.orderIncrease(shareId);
        }
        else if (type == ShareDataTypeEnum.成交) {
            this.shareService.dealIncrease(shareId);
        }
    }

    public void action(Long shareId, ShareDataTypeEnum type, Long userId, String content, Long businessId) {
        ShareData shareData = new ShareData();
        shareData.setBusinessId(businessId);
        shareData.setUserId(userId);
        shareData.setShareId(shareId);
        shareData.setType(type.getCode());
        shareData.setContent(content);
        shareData.setCtime(new Date());
        this.shareDataMapper.insert(shareData);
        this.updateShare(shareData.getShareId(), ShareDataTypeEnum.findByCode(shareData.getType()).get());
    }

    /**
     * 成交行为调用
     * @param orderId
     */
    public void dealed(Long orderId, String content) {
        ShareData shareData = this.findByBusinessIdAndType(orderId, ShareDataTypeEnum.下单);
        if (shareData != null) {
            this.action(shareData.getShareId(), ShareDataTypeEnum.成交, shareData.getUserId(), content,  orderId);
            this.updateShare(shareData.getShareId(), ShareDataTypeEnum.findByCode(shareData.getType()).get());
        }
    }

    private ShareData findByBusinessIdAndType(Long orderId, ShareDataTypeEnum type) {
        return this.shareDataMapper.findByBusinessIdAndType(orderId, type.getCode());
    }

    public PageInfo<ShareDataVo> findList(Date startTime, Date endTime, int pageSize, int pageNum) {
        PageInfo<ShareDataVo> pageInfo = PageHelper.startPage(pageNum, pageSize)
                .doSelectPageInfo(() -> this.shareDataMapper.findList(startTime, endTime));
        pageInfo.getList().stream().forEach(vo -> {
            Optional<ShareDataTypeEnum> typeEnum = ShareDataTypeEnum.findByCode(vo.getType());
            if (typeEnum.isPresent()) {
                vo.setTypeCn(typeEnum.get().getDesc());
                vo.setDataUserPhone(PhoneNumberUtil.getSecPhone(vo.getDataUserPhone()));
//                vo.setShareUserPhone(PhoneNumberUtil.getSecPhone(vo.getShareUserPhone()));
            }
        });
        return pageInfo;
    }

    public UploadResult export(Date startTime, Date endTime, Long userId) {
        List<ShareDataVo> list = this.shareDataMapper.findList(startTime, endTime);
        list.stream().forEach(vo -> {
            Optional<ShareDataTypeEnum> typeEnum = ShareDataTypeEnum.findByCode(vo.getType());
            if (typeEnum.isPresent()) {
                vo.setTypeCn(typeEnum.get().getDesc());
                vo.setDataUserPhone(PhoneNumberUtil.getSecPhone(vo.getDataUserPhone()));
                vo.setShareUserPhone(PhoneNumberUtil.getSecPhone(vo.getShareUserPhone()));
            }
        });

        List headers = getHeaders();
        String fileName = UUID.randomUUID().toString() + ".xlsx";
        File file = new File( System.getProperty("java.io.tmpdir") + "/" + fileName);
        try {
            ExcelConfig config1 = new ExcelConfig("分销数据导出", headers, list);
            List<ExcelConfig> configs = new ArrayList();
            configs.add(config1);
            long time = System.currentTimeMillis();
            ExcelUtil.write(file, configs);
            log.info("导出文件成功，time=" + (System.currentTimeMillis() - time));
        } catch (IOException e) {
            log.error(e.getMessage(), e);
            throw new StandardBusinessException(e.getMessage());
        }
        return this.fileService.upload(userId, file, fileName);
    }

    private static List<ExcelHeader> getHeaders() {
        CellInfo info = new CellInfo();
        info.setColor(Colors.RED);
        info.setDataFormat("yyyy-MM-dd");
        CellInfo info1 = new CellInfo();
        info1.setColor(Colors.RED);
        info1.setFillColor(Colors.LIGHT_ORANGE.getIndex());
        info1.setDataFormatIndex(Integer.decode("0x31").shortValue());
        CellInfo info2 = new CellInfo();
        info2.setColor(Colors.BLUE);
        info2.setDataFormat("#,##0.00");
        CellInfo headInfo = new CellInfo();
        headInfo.setFillColor(Colors.RED.getIndex());
        headInfo.setColor(Colors.YELLOW);
        CellInfo headInfo1 = new CellInfo();
        headInfo1.setFillColor(Colors.BLUE_GREY.getIndex());
        headInfo1.setColor(Colors.RED);
        List<ExcelHeader> headers = new ArrayList();
        ExcelHeader h1 = null;
//        h1 = new ExcelHeader("年龄", "age", 1, 1, 1, 1);
//        headers.add(h1);
//        h1.setCellInfo(info1);
//        h1 = new ExcelHeader("姓名", "name", 1, 1, 1, 2);
//        headers.add(h1);
//        h1 = new ExcelHeader("年份", "year", 1, 1, 1, 3);
//        headers.add(h1);
//        h1.setCellInfo(info2);
//        h1 = new ExcelHeader("月份", "month", 1, 1, 1, 4);
//        headers.add(h1);
//        h1 = new ExcelHeader("生日", "birthday", 1, 1, 1, 5);
//        headers.add(h1);
//        h1.setCellInfo(info);
        h1 = new ExcelHeader("类型", "typeCn", 1, 1, 1, 1);
        headers.add(h1);

        h1 = new ExcelHeader("用户手机号", "dataUserPhone", 1, 1, 1, 2);
        headers.add(h1);

        h1 = new ExcelHeader("发生时间", "ctime", 1, 1, 1, 3);
        headers.add(h1);

        h1 = new ExcelHeader("分销员手机号", "shareUserPhone", 1, 1, 1, 4);
        headers.add(h1);

        h1 = new ExcelHeader("分销员", "shareUserName", 1, 1, 1, 5);
        headers.add(h1);

        h1 = new ExcelHeader("商品id", "merchId", 1, 1, 1, 6);
        headers.add(h1);

        h1 = new ExcelHeader("商品名称", "merchName", 1, 1, 1, 7);
        headers.add(h1);
        return headers;
    }
}
